package com.example.springbootcaffeinedemo.common;
import com.github.benmanes.caffeine.cache.AsyncLoadingCache;
import com.github.benmanes.caffeine.cache.Caffeine;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * Created by IntelliJ IDEA2022.3.2
 * @Author: Tenghw
 * @Date: 2023/04/17  19:19
 * @Description: 缓存添加策略之自动异步加载
 */
public class CaffeineCacheAddPolicy4 {
    private static Object createObject(String key){
        return "hello caffeine 2023";
    }
    public static void main(String[] args) throws InterruptedException {
        AsyncLoadingCache<String, Object> cache = Caffeine.newBuilder()
                .expireAfterWrite(2, TimeUnit.SECONDS)
                .buildAsync(key -> key + "-" + System.currentTimeMillis());
        // 1、若获取不存在的key时，会使用buildAsync()方法中的算法计算出value,并存入缓存
        CompletableFuture<Object> future = cache.get("key1");
        future.thenAccept(o-> System.out.println(System.currentTimeMillis()+">>> " + o));

        TimeUnit.SECONDS.sleep(3);

        // 2、key不存在则返回null
        CompletableFuture<Object> key2 = cache.getIfPresent("key2");
        System.out.println("key2: " +key2);
    }
}
